#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    socket = new QTcpSocket;
    socket->connectToHost("192.168.0.104",8086);
    //connect(ui->pushButton_login,SIGNAL(clicked()),this,SLOT(LoginFunction()));
    connect(ui->pushButton_logon,SIGNAL(clicked()),this,SLOT(LogonFunction()));
    connect(ui->pushButton_login,SIGNAL(clicked()),this,SLOT(LoginFunction()));
    ui->lineEdit_password->setEchoMode(QLineEdit::Password);
    qDebug()<<"test";
}



MainWindow::~MainWindow()
{
    if(chat)
        delete chat;
    if(loginframe)
       delete loginframe;
  /*  if(socket)
        delete socket;*/
    delete ui;
}

void MainWindow::LogonFrame()
{
    this->disconnect(socket,SIGNAL(readyRead()),0,0);
    chat = new Chat(socket);
    this->hide();

     //disconnect(socket,0,0,0);
    chat->setInfo(username);
  //

    chat->show();
    connect(socket,SIGNAL(readyRead()),chat,SLOT(DealreqAnswer()));
    chat->getFriendList();


}



void MainWindow::LogonFunction()
{
    Logon logon;
    username = ui->lineEdit_username->text();
    QString password = ui->lineEdit_password->text();
    sprintf(logon.username,username.toStdString().c_str());
    sprintf(logon.password,password.toStdString().c_str());

    int res = socket->write((const char *)&logon,MSG_LENGTH);
    if(res < 0)
    {
        QMessageBox::critical(this,"error","错误");
    };
    connect(socket,SIGNAL(readyRead()),this,SLOT(DealAnswer()));
}

void MainWindow::LoginFunction()
{
    loginframe = new LoginFrame;
    loginframe->setSocket(this->socket);
    loginframe->setPtr(&(this->_isLogonFlag),&(this->username));

    loginframe->show();
    this->hide();
    loginframe->exec();
    this->show();
  //  qDebug()<<_isLogonFlag <<&(this->_isLogonFlag);
    //QMessageBox(this,"fff",QString::number(_isLogonFlag));
    if(this->_isLogonFlag == 1)
    {
        this->disconnect(socket,SIGNAL(readyRead()),0,0);
        chat = new Chat(socket);
        this->hide();

         //disconnect(socket,0,0,0);
        chat->setInfo(username);
       // chat->getFriendList();

        chat->show();
        connect(socket,SIGNAL(readyRead()),chat,SLOT(DealreqAnswer()));
        chat->getFriendList();


    }

}

void MainWindow::DealAnswer()
{
   // QMessageBox::information(this,"ok","ok");
    QByteArray array = socket->readAll();
    char * ptr = array.data();
    Answer * answer = (Answer *)ptr;
    switch (answer->cmd)
    {
    case CMD_LOGIN_ANSWER:
        break;
    case CMD_LOGON_ANSWER:
        if(answer->answer == true)
        {
            LogonFrame();
        }else
        {
            QMessageBox::information(this,"提醒","登陆失败");
        }
        break;
    }
}
